package com.example.micro.thread.reentrantlock;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockDemo {

    private ReentrantLock lock = new ReentrantLock();
    private List<Integer> list = new ArrayList<>();
    private Condition condition = lock.newCondition();

    private void test() {

        Thread thread1 = new Thread(
                () -> {
                    lock.lock();
                    try {
                        list.add(1);
                        condition.await();
                        list.add(2);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        list.add(3);
                        lock.unlock();
                    }
                }
        );

        Thread thread2 = new Thread(
                () -> {
                    lock.lock();
                    try {
                        list.add(2);
                    } finally {
                        lock.unlock();
                    }
                }
        );

        thread1.start();
        thread2.start();


    }

    public static void main(String[] args) {
        new ReentrantLockDemo().test();
    }

}
